var ctx = localStorage.getItem("ctx");
var table = '';
$(function() {
	
	
	juicer.set({
	    'tag::operationOpen': '-~',
	    'tag::operationClose': '+',
	    'tag::interpolateOpen': '#-',
	    'tag::interpolateClose': '+',
	    'tag::noneencodeOpen': '##-',
	    'tag::noneencodeClose': '+',
	    'tag::commentOpen': '-*',
	    'tag::commentClose': '+'
	});
	
	var wholerolenamesearch = '';
	var editRoleId = '';
	
	//获取table
	roleTable('');
	
	
	//根据角色名称查询
	$(".btn-search").on("click", function() {
		wholerolenamesearch = $(".searchrolename").val();
		table.destroy();
		//查询获取table
		roleTable(wholerolenamesearch);
		
	});
	
	//添加角色显示模态框
	$(".btn-add").on("click", function() {
		$("#myModalAdd").modal('show');
	});
	$("#addroleform").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	addrolename: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            addroleEnName: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            }
        }
	});
	//确认添加角色
	$(".btn-addrole").on("click", function() {
		
		var roleType = $(".addroleTypeSelect").find("option:selected").attr("value");//角色类型
		var dataScope = $(".adddataScopeSelect").find("option:selected").attr("value");//数据范围
		var roleName = $(".addrolename").val();//角色名称
		var roleEnName = $(".addroleEnName").val();//英文角色名称
		var remarks = $(".addremarks").val();//备注信息
		var roleStatus = $(".addrolestatus").find("input:checked").attr("value");//角色状态
		
		confirmaddrole(roleType,dataScope,roleName,roleEnName,remarks,roleStatus);
	});
	
	//修改详情和确认修改
	$(document).on("click", ".btn-edit", function() {
		var data = table.row( $(this).parents('tr') ).data();
		editRoleId = data.sysRoleId;
		console.log(data);
		$(".editroleTypeSelect").find("option[value="+data.roleType+"]").attr('selected', true);
		$(".editdataScopeSelect").find("option[value="+data.dataScope+"]").attr('selected', true);
		$(".editrolename").val(data.roleName);
		$(".editroleEnName").val(data.roleEnName);
		$(".editremarks").val(data.remarks);
		$(".editrolestatus").find("input[value="+data.roleStatus+"]").attr("checked", true);
		
		$("#myModalEdit").modal('show');
	});
	$("#editroleform").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	editrolename: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            editroleEnName: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            }
        }
	});
	//确认修改
	$(".edit-save-btn").on("click", function() {
		var roleType = $(".editroleTypeSelect").find("option:selected").attr("value");//角色类型
		var dataScope = $(".editdataScopeSelect").find("option:selected").attr("value");//数据范围
		var roleName = $(".editrolename").val();//角色名称
		var roleEnName = $(".editroleEnName").val();//英文角色名称
		var remarks = $(".editremarks").val();//备注信息
		var roleStatus = $(".editrolestatus").find("input:checked").attr("value");//角色状态
		confirmeditrole(roleType,dataScope,roleName,roleEnName,remarks,roleStatus,editRoleId);
	});
	
	//查看详情
	$(document).on("click", ".btn-detail", function() {
		var data = table.row( $(this).parents('tr') ).data();
		console.log(data);
		if(data.roleType == 1){
			$(".detailroleType").html("超级管理员");
		}
		if(data.roleType == 2){
			$(".detailroleType").html("普通管理员");
		}
		if(data.dataScope == 1) {
			$(".dataildataScope").html("所有数据");
		}
		if(data.dataScope == 2) {
			$(".dataildataScope").html("所在公司及以下数据");
		}
		if(data.dataScope == 3) {
			$(".dataildataScope").html("所在公司数据");
		}
		if(data.dataScope == 4) {
			$(".dataildataScope").html("所在部门及以下数据");
		}
		if(data.dataScope == 5) {
			$(".dataildataScope").html("所在部门数据");
		}
		if(data.dataScope == 6) {
			$(".dataildataScope").html("仅本人数据");
		}
		if(data.roleStatus == 0) {
			$(".detailroleStatus").html("不可用");
		}
		if(data.roleStatus == 1) {
			$(".detailroleStatus").html("可用");
		}
		$(".detailrolename").html(data.roleName);
		$(".detailroleEnName").html(data.roleEnName);
		$(".detailremarks").html(data.remarks);
		$(".detailcreateTime").html(data.createTime);
//		$(".detailcreateUserId").html(data.createUserId);
//		$(".detailsysRoleId").html(data.sysRoleId);
		$(".detailupdateTime").html(data.updateTime);
//		$(".detailupdateUserId").html(data.updateUserId);
		
		$("#myModalDetail").modal('show');
	});
	
	//授权
	$(document).on("click", ".btn-authorize", function() {
		var data = table.row( $(this).parents('tr') ).data();
		editRoleId = data.sysRoleId;

		$.ajax({
			type: 'POST',
			url: ctx+'/resource/menuList',
			dataType: 'json',
			success: function(data) {
				console.log(data);
				var setting = {
					check: {
						enable: true
					},
					data: {
						key: {
							name: 'menuName'
						},
						simpleData: {
							enable:true,
							idKey: "sysMenuId",
							pIdKey: "parentId",
							rootPId: ""
						}
					}
				};
//				setting.check.chkboxType = {
//					"Y": "s",
//					"N": "s"
//				};
				var zNodes = data;
				$.fn.zTree.init($("#treeWaterLayer"), setting, zNodes);
				
				$.ajax({
					type: 'POST',
					url: ctx+'/sys/v1/role/getAccreditList',
					dataType: 'json',
					data: {
						sysRoleId: editRoleId
					},
					success: function(data2) {
						var treeObj = $.fn.zTree.getZTreeObj("treeWaterLayer");
						var node = treeObj.getNodeByParam("sysMenuId", 4, null);
						for(var i=0; i<data2.length; i++) {
							var node = treeObj.getNodeByParam("sysMenuId", data2[i].sysMenuId);
							treeObj.checkNode(node);//指定选中ID的节点  
							treeObj.expandNode(node, true, false);//指定选中ID节点展开
						}
					}
				});
				
				
				
				
			}
		});

		$("#myModalAuthorize").modal('show');
	});
	
	
	//确认授权
	$('.confirm-authorize').on('click', function() {
		var treeObj = $.fn.zTree.getZTreeObj("treeWaterLayer");
		var nodes = treeObj.getCheckedNodes(true);
//		console.log(nodes);
		var sysMenuIds = [];
		$.each(nodes, function(k, v) {
			sysMenuIds.push(v.sysMenuId);
		});
		console.log(sysMenuIds);
		$.ajax({
			type: 'POST',
			url: ctx+'/sys/v1/role/accredit',
			dataType: 'json',
			data: {
				sysRoleId: editRoleId,
				sysMenuIds: sysMenuIds
			},
			success: function(data) {
				console.log(data);
				if(data == true) {
					alert("授权成功");
					$("#myModalAuthorize").modal('hide');
				}
				else {
					alert("授权失败");
				}
			}
		});
	});
	
	
	
	
	//删除
	$(document).on("click", ".btn-delete", function() {
		var data = table.row( $(this).parents('tr') ).data();
		editRoleId = data.sysRoleId;
		$.ajax({
			type: 'POST',
			url: ctx+'/sys/v1/role/del',
			dataType: 'json',
			data: {
				sysRoleId: editRoleId
			},
			success: function(data) {
				console.log(data);
				if(data == true) {
					alert("删除成功");
					window.location.reload();
				}
				else {
					alert("删除失败");
				}
			}
		});
	});
	
	//禁用与启用
	$(document).on("click", ".btn-forbid", function() {
		var data = table.row( $(this).parents('tr') ).data();
		editRoleId = data.sysRoleId;
		var state = data.roleStatus;
		if(state == 1) {
			roleState(0, editRoleId);
		}
		else {
			roleState(1, editRoleId);
		}
	});
	
	
	function roleState(state, editRoleId) {
		$.ajax({
			type: 'POST',
			url: ctx+'/sys/v1/role/state',
			dataType: 'json',
			data: {
				state: state,
				sysRoleId: editRoleId
			},
			success: function(data) {
				console.log(data);
				if(data == true) {
					alert("修改状态成功");
					window.location.reload();
				}
				else {
					alert("修改状态失败");
				}
			}
		});
	}
	
	//确认添加角色
	function confirmaddrole(roleType,dataScope,roleName,roleEnName,remarks,roleStatus) {
		$('#addroleform').data('bootstrapValidator').validate();  
        if(!$('#addroleform').data('bootstrapValidator').isValid()){  
            return ;  
        }
		$.ajax({
			type: 'POST',
			url: ctx+'/sys/v1/role/add',
			dataType: 'json',
			data: {
				roleType: roleType,
				dataScope: dataScope,
				roleName: roleName,
				roleEnName: roleEnName,
				remarks: remarks,
				roleStatus: roleStatus
			},
			success: function(data) {
    			console.log(data);	
    			alert('添加成功');
    			location.replace(location.href);

    		},
    		error: function(data) {
    			alert(data.responseJSON.message);
    		}
		});
	}
	
	//确认修改角色
	function confirmeditrole(roleType,dataScope,roleName,roleEnName,remarks,roleStatus,editRoleId) {
		$('#editroleform').data('bootstrapValidator').validate();  
        if(!$('#editroleform').data('bootstrapValidator').isValid()){  
            return ;  
        }
		$.ajax({
			type: 'POST',
			url: ctx+'/sys/v1/role/update',
			dataType: 'json',
			data: {
				roleType: roleType,
				dataScope: dataScope,
				roleName: roleName,
				roleEnName: roleEnName,
				remarks: remarks,
				roleStatus: roleStatus,
				sysRoleId: editRoleId
			},
			success: function(data) {
    			console.log(data);	
    			alert('修改成功');
    			location.replace(location.href);

    		},
    		error: function(data) {
    			alert(data.responseJSON.message);
    		}
		});
	}
	
});